<template>
	<a-card title="房东档期管理" :body-style="{ padding: none }">
		<!-- 筛选区域 -->
		<div class="filter-container">
			<a-form layout="inline">
				<a-form-item label="忽略已过期的日期" required>
					<a-select v-model:value="filterIsFuture" placeholder="请选择" @change="loadSchedules">
						<a-select-option :value="true">是</a-select-option>
						<a-select-option :value="false">否</a-select-option>
					</a-select>
				</a-form-item>
			</a-form>
		</div>
		<div class="schedule-container">
			<!-- 左侧：日期列表 + 分页 -->
			<div class="date-list">
				<h3 style="text-align: center;">请选择日期</h3>
				<a-list :data-source="paginatedDates" bordered class="date-list-box">
					<template #renderItem="{ item }">
						<a-list-item :class="{ 'date-item': true, active: selectedDate === item }" @click="selectDate(item)">
							{{ item }}
						</a-list-item>
					</template>
				</a-list>
				<a-pagination
					style="text-align: center; margin-top: 12px"
					:current="datePagination.current"
					:page-size="datePagination.pageSize"
					:total="totalDates"
					@change="(page) => (datePagination.current = page)"
				/>
			</div>

			<!-- 右侧：选中日期下的时段列表 -->
			<div class="time-slot-container" v-if="selectedDate">
				<h3 style="text-align: center;">{{ selectedDate }} 的档期</h3>
				<a-table :columns="columns" :data-source="filteredSchedules" :pagination="false" row-key="id" bordered>
					<template #action="{ record }" >
						<a @click="openUpdateModal(record)">修改状态</a>
					</template>
				</a-table>
			</div>
		</div>

		<!-- 修改状态 Modal -->
		<a-modal
			v-model:visible="updateModalVisible"
			title="修改档期状态"
			@ok="confirmUpdateStatus"
			@cancel="cancelUpdateStatus"
			ok-text="确认修改"
			cancel-text="取消"
			centered
		>
			<a-form layout="vertical">
				<a-form-item label="当前时段" required>
					<div style="border: solid 1px rgba(0, 0, 0, 0.2); padding: 6px 6px 6px 10px; border-radius: 7px">
						{{ formatDate(currentSchedule?.scheduleDate) }}
						{{ currentSchedule?.startTime }} - {{ currentSchedule?.endTime }}
					</div>
				</a-form-item>
				<a-form-item label="新状态" required>
					<a-select v-model:value="newStatus" placeholder="请选择新状态">
						<a-select-option value="available">可预约</a-select-option>
						<a-select-option value="forbid">不可预约</a-select-option>
						<!-- 当状态为 booked 时，设置显示为已被预约 -->
						<a-select-option v-if="newStatus === 'booked'" value="booked" disabled>已被预约</a-select-option>
					</a-select>

				</a-form-item>

				<!-- 只有当状态是 booked 时，才显示拒绝理由 -->
				<a-form-item v-if="newStatus === 'forbid' && currentSchedule?.status === 'booked'" label="拒绝理由" required>
					<a-input v-model:value="reason" placeholder="请输入拒绝理由" />
				</a-form-item>
			</a-form>
		</a-modal>
	</a-card>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue';
import dayjs from 'dayjs';
import landlordApi from '@/api/landlordApi';

const schedules = ref([]);
const selectedDate = ref('');
const updateModalVisible = ref(false);
const currentSchedule = ref(null);
const newStatus = ref('');
const reason = ref(''); // 新增字段：拒绝理由

// 筛选变量：是否忽略过期，默认传 true（即不忽略过期）
const filterIsFuture = ref(true);

// 左侧日期列表分页
const datePagination = reactive({ current: 1, pageSize: 7 });

const loadSchedules = () => {
	landlordApi
		.getLandlordAllSchedules(filterIsFuture.value)
		.then((res) => {
			if (res.code === 200) {
				schedules.value = Array.isArray(res.data.schedules) ? res.data.schedules : [];
			} else {
				schedules.value = [];
				message.error(res.message);
			}
		})
		.catch(() => {
			schedules.value = [];
			message.error('获取档期失败');
		});
};

const uniqueDates = computed(() =>
	Array.from(new Set(schedules.value.map((s) => dayjs(s.scheduleDate).format('YYYY-MM-DD')))).sort()
);

const paginatedDates = computed(() => {
	const start = (datePagination.current - 1) * datePagination.pageSize;
	return uniqueDates.value.slice(start, start + datePagination.pageSize);
});

const totalDates = computed(() => uniqueDates.value.length);

const filteredSchedules = computed(() =>
	schedules.value.filter((s) => dayjs(s.scheduleDate).format('YYYY-MM-DD') === selectedDate.value)
);

const columns = computed(() => {
	const baseColumns = [
		{
			title: '日期',
			dataIndex: 'scheduleDate',
			key: 'scheduleDate',
			customRender: ({ text }) => dayjs(text).format('YYYY-MM-DD')
		},
		{ title: '开始时间', dataIndex: 'startTime', key: 'startTime' },
		{ title: '结束时间', dataIndex: 'endTime', key: 'endTime' },
		{
			title: '档期状态',
			dataIndex: 'status',
			key: 'status',
			customRender: ({ text }) => ({
				available: '可预约',
				booked: '已被预约',
				forbid: '不可预约',
				expired: '已过期'
			}[text] || '未知状态')
		}
	];

	// 只有当状态不是 expired 时，才添加操作列
	if (selectedDate.value && filteredSchedules.value.some((schedule) => schedule.status !== 'expired')) {
		baseColumns.push({
			title: '操作',
			key: 'action',
			slots: { customRender: 'action' }
		});
	}

	return baseColumns;
});

const selectDate = (date) => (selectedDate.value = date);

const openUpdateModal = (schedule) => {
	currentSchedule.value = schedule;
	newStatus.value = schedule.status;
	reason.value = ''; // 清空拒绝理由
	updateModalVisible.value = true;
};

const confirmUpdateStatus = () => {
	if (!newStatus.value) return message.error('请选择新状态');
	if (newStatus.value === 'forbid' && currentSchedule.value.status === 'booked' && !reason.value) {
		return message.error('请输入拒绝理由');
	}

	Modal.confirm({
		title: '确认修改档期状态？',
		okText: '确认',
		cancelText: '取消',
		onOk() {
			landlordApi
				.updateSchedule({
					scheduleId: currentSchedule.value.id,
					newStatus: newStatus.value,
					reason: reason.value // 传递拒绝理由
				})
				.then((res) => {
					if (res.code === 200) {
						message.success('更新成功');
						updateModalVisible.value = false;
						loadSchedules();
					} else {
						message.error(res.message);
					}
				})
				.catch(() => {
					message.error('更新失败');
				});
		}
	});
};

const cancelUpdateStatus = () => (updateModalVisible.value = false);

const formatDate = (date) => dayjs(date).format('YYYY-MM-DD');

onMounted(() => {
	loadSchedules();
});
</script>

<style scoped>
.schedule-container {
	display: flex;
}

.date-list {
	width: 200px;
	margin-right: 24px;
}

.date-list-box {
	max-height: 500px;
	overflow-y: auto;
}

.date-item {
	padding: 8px;
	cursor: pointer;
	justify-content: center;
}

.date-item:hover {
	background: #e6f7ff;
}

.date-item.active {
	background: #e6f7ff;
}

.time-slot-container {
	flex: 1;
}

.filter-container {
	margin-top: -1rem;
}
</style>
